const STORAGE_KEY = "macos"
const enCodeKey = (stringToEncode) => window.btoa(stringToEncode)

/**
 * add a data item to localStorage
 * @param {String} keyName a key name
 * @param {String | Object} keyValue value
 */
const setItem = (keyName, keyValue) => {
  let value
  if (keyValue instanceof Object) {
    value = JSON.stringify(keyValue)
  } else {
    value = keyValue
  }
  window.localStorage.setItem(`_${STORAGE_KEY}_${enCodeKey(keyName)}`, value)
}

/**
 * read the localStorage item
 * @param {String} keyName a key name
 * @returns any
 */
const getItem = (keyName) => {
  let value = window.localStorage.getItem(`_${STORAGE_KEY}_${enCodeKey(keyName)}`) || ""
  try {
    value = JSON.parse(value)
  } catch (e) {
    return value
  }
  return value
}

/**
 * remove the localStorage item
 * @param {String} keyName a key name
 */
const removeItem = (keyName) => {
  window.localStorage.removeItem(`_${STORAGE_KEY}_${enCodeKey(keyName)}`)
}

/**
 * remove all the localStorage items
 */
const removeAll = () => {
  window.localStorage.clear()
}

export default { setItem, getItem, removeItem, removeAll }
